using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;

namespace AutoClicker
{
    public partial class MainForm : Form
    {
        // 在MainForm类中添加以下字段初始化
        private readonly MouseRecorder recorder;
        private readonly MousePlayer player;
        private List<MouseAction> recordedActions;
        private string currentScriptPath;

        public MainForm()
        {
            // 初始化所有字段
            recorder = new MouseRecorder();
            player = new MousePlayer();
            recordedActions = new List<MouseAction>();
            currentScriptPath = string.Empty;

            InitializeComponent();

            recorder.ActionRecorded += (action) =>
            {
                if (InvokeRequired)
                {
                    Invoke(new Action<MouseAction>(a =>
                    {
                        recordedActions.Add(a);
                        lstActions.Items.Add(a.ToString());
                    }), action);
                }
                else
                {
                    recordedActions.Add(action);
                    lstActions.Items.Add(action.ToString());
                }
            };

            player.PlaybackStatusChanged += (status) =>
            {
                if (InvokeRequired)
                {
                    Invoke(new Action<string>(s => lblStatus.Text = s), status);
                }
                else
                {
                    lblStatus.Text = status;
                }
            };

            RegisterHotKeys();
        }

        private void RegisterHotKeys()
        {
            HotKeyManager.RegisterHotKey(this.Handle, 100, HotKeyManager.KeyModifiers.None, Keys.F6);
            HotKeyManager.RegisterHotKey(this.Handle, 101, HotKeyManager.KeyModifiers.None, Keys.F7);
            HotKeyManager.RegisterHotKey(this.Handle, 102, HotKeyManager.KeyModifiers.None, Keys.F8);
            HotKeyManager.RegisterHotKey(this.Handle, 103, HotKeyManager.KeyModifiers.None, Keys.F9);
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;

            if (m.Msg == WM_HOTKEY)
            {
                switch (m.WParam.ToInt32())
                {
                    case 100: // F6
                        btnStartRecording.PerformClick();
                        break;
                    case 101: // F7
                        btnStopRecording.PerformClick();
                        break;
                    case 102: // F8
                        btnPlay.PerformClick();
                        break;
                    case 103: // F9
                        btnStop.PerformClick();
                        break;
                }
            }
            base.WndProc(ref m);
        }

        private void btnStartRecording_Click(object sender, EventArgs e)
        {
            lstActions.Items.Clear();
            recordedActions.Clear();
            recorder.StartRecording();
            btnStartRecording.Enabled = false;
            btnStopRecording.Enabled = true;
            lblStatus.Text = "正在录制...";
        }

        private void btnStopRecording_Click(object sender, EventArgs e)
        {
            recorder.StopRecording();
            btnStartRecording.Enabled = true;
            btnStopRecording.Enabled = false;
            lblStatus.Text = "录制完成";
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            if (recordedActions.Count == 0)
            {
                MessageBox.Show("没有录制的动作可以播放", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            bool loop = chkLoop.Checked;
            int speed = (int)nudSpeed.Value;
            player.PlayActions(recordedActions, loop, speed);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            player.StopPlaying();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            lstActions.Items.Clear();
            recordedActions.Clear();
            lblStatus.Text = "已清空动作列表";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "Auto Clicker Script (*.acs)|*.acs|All Files (*.*)|*.*";
                sfd.DefaultExt = "acs";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        var options = new JsonSerializerOptions
                        {
                            WriteIndented = true,
                            Converters = { new JsonStringEnumConverter() }
                        };
                        string json = JsonSerializer.Serialize(recordedActions, options);
                        File.WriteAllText(sfd.FileName, json);
                        currentScriptPath = sfd.FileName;
                        lblStatus.Text = $"脚本已保存: {Path.GetFileName(sfd.FileName)}";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"保存脚本失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        // 修改JSON反序列化部分，添加null检查
        private void btnLoad_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "Auto Clicker Script (*.acs)|*.acs|All Files (*.*)|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        string json = File.ReadAllText(ofd.FileName);
                        var options = new JsonSerializerOptions
                        {
                            Converters = { new JsonStringEnumConverter() }
                        };
                        var actions = JsonSerializer.Deserialize<List<MouseAction>>(json, options);

                        // 添加null检查
                        if (actions != null)
                        {
                            recordedActions = actions;
                            lstActions.Items.Clear();
                            foreach (var action in recordedActions)
                            {
                                lstActions.Items.Add(action.ToString());
                            }
                            currentScriptPath = ofd.FileName;
                            lblStatus.Text = $"脚本已加载: {Path.GetFileName(ofd.FileName)}";
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载脚本失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        // 修复第173行可能的null引用问题
        private void btnRunScript_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(currentScriptPath))  // 修复CS8601
            {
                btnLoad.PerformClick();
                btnPlay.PerformClick();
            }
            else
            {
                MessageBox.Show("没有当前脚本可运行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (AboutForm aboutForm = new AboutForm())
            {
                aboutForm.ShowDialog();
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            recorder?.Dispose(); // 添加null检查
            player?.Dispose();   // 添加null检查

            // 注销所有快捷键
            HotKeyManager.UnregisterHotKey(this.Handle, 100);
            HotKeyManager.UnregisterHotKey(this.Handle, 101);
            HotKeyManager.UnregisterHotKey(this.Handle, 102);
            HotKeyManager.UnregisterHotKey(this.Handle, 103);
        }
    }
}